import zipfile

from win32com.client import GetObject
import subprocess
import os,sys

PROCNAME = "SSHClient_WX.exe"
APP_NAME = 'SSHClient_WX'
FILE = 'SSHClient_WX.zip'

def killApp():
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        for proc in processes:
            if proc.Properties_("Name").Value == PROCNAME:
                proc.Terminate
                
def currentDer():
        print "currentDer: "+os.path.dirname(sys.argv[0]).replace('\\','/')
        return os.path.dirname(sys.argv[0]).replace('\\','/')


def openApp():
    temp = currentDer()+"/"+PROCNAME
    print temp
    subprocess.call(temp)

    
def unzipfile():
        
    currentDers = currentDer()
    currentDers = currentDers +'/'
    print currentDers
    rs = False
    global  persent, var, f, FILE
    
    try :
        print currentDers+FILE
       
        zf = zipfile.ZipFile(currentDers+FILE)
        i = 0
        print '1'
        for name in zf.namelist():
            #currentSize = f.size(currentDers+FILE)
            print name
            if  name.find("/")>-1:
                a=name.split('/')
                print a[0]
                print a[1]
                if not os.path.exists(currentDers+a[0]):
                    os.mkdir(currentDers+a[0])
                try:
                    outfile = open(os.path.join(currentDers+a[0],a[1]), 'wb')
                    outfile.write(zf.read(name))
                except Exception as inst:
                    print "unzip: "+str(inst)        
            else:
                try:
                    #print name 
                    #print 'b'
                    #os.remove(os.path.join(currentDers,name))
                    
                    outfile = open(os.path.join(currentDers,name), 'wb')
                    outfile.write(zf.read(name))
                except Exception as inst:
                    print "unzip: "+str(inst)
                
            i = i+1
            #currentsize = os.path.getsize(currentDers+APP_NAME)
            #var.set("Extracting "+currentsize)
            #persent.create_rectangle(currentsize, 0, 0, 25, fill = "green")
            #dowloading.update()
            
        rs = True
                   
    except  Exception as inst:
        print inst

    #dowloading.destroy()
    #self.openApp()
    return rs
try:
        print '1'
        killApp()
except:
        pass

try:
        print '2'
        unzipfile()
except:
        pass
try:
        print '3'
        openApp()
except:
        pass






